/*
* Copyright (c) 2009, Active Web Solutions Limited
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1- Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2- Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3- The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY Active Web Solutions Limited ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Active Web Solutions Limited BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package net.aws.jazure.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * A Helper class for HTTP requests.
 * 
 * @author dyaa.albakour
 *
 */
public class RestHelper {

	
	/**
	 * Construct a URL giving a base URI string and a set of key-value parameters
	 * 
	 * @param baseuri the base URL string
	 * @param parameters a Map of key-value parameters
	 * @return A string representing the constructed URL
	 * @throws UnsupportedEncodingException If the UTF-8 encoding is not available!
	 */
	public static String createRequestURI(String baseuri, Map<String,String> parameters) 
		throws UnsupportedEncodingException{
		
		// At the moment the implementation doesn't make use of a URI builder
		// (e.g the one here: https://hppsys.passport.hp.com/hp_docs/xmltools/xalan_manual/apidocs/org/apache/xml/utils/URI.html)
		//
		// we might improve this by using the URI class.
		//
		// Also, maybe contact Neolios to add support of the URI class?		
		StringBuilder builder = new StringBuilder();		
		builder.append(baseuri);
		boolean firstParam = true;	
		for(String key:parameters.keySet()){
			builder.append(firstParam?"?":"&");
			builder.append(URLEncoder.encode(key, "UTF-8"));
			builder.append("=");
			builder.append(URLEncoder.encode((String)parameters.get(key), "UTF-8"));				
			firstParam = false;
		}		
		return builder.toString();
		
	}
	
}
